# coding:utf-8

# """
# @Time : 2023/06/25 16:31
# @Auth : WangJingbo
# @File : app.py
# @Desc : 派单分类接口 129类别
# """
import time
import traceback
from typing import Optional,Union
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
import uvicorn
from inference_paidan import inference,danwei_id
import pandas as pd 

import config
from logger import configure_logging

keyword = pd.read_excel(config.keyword_path)

app = FastAPI()

logger = configure_logging()

#诉求地址 4级分类 工单内容  ','拼接
class MatchInput(BaseModel):
    appealRegion: str 
    classId: Union[str, None] = None
    content: str
    class4: str
    
@app.post("/infer")
async def infer(item: MatchInput):  # item需要与MatchInput对象定义保持一致
#     """
#     获取派单类别
#     """
    start_time = time.time()
    result = dict()
    flag = False
    try:
        address= item.appealRegion
        # classId = item.classId
        text = item.content
        class4 = item.class4
        new_class4 = class4.replace('-',',')
        data = address + ',' + new_class4 + ',' + text 
        assert text, 'The `text` parameter cannot be empty.'
        logger.debug(data)
        
        # 关键词检索
        if "一网通办" in new_class4:
            for item in keyword.values.tolist():
                label,key_words = item
                key_words = key_words.split('、')
                for key_word in key_words:
                    if key_word in text:
                        res = danwei_id[label]
                        flag = True
                        break
                if flag:
                    break
            if not flag:
                res = inference(data)
        # 模型推理
        else:
            res = inference(data)
        
        result['code'] = 200
        # result['id'] = classId
        result['msg'] = 'success'
        result['class'] = res
        

    except Exception as e:
        traceback.print_exc()
        result['code'] = 500
        result['msg'] = e.__str__()
        logger.error(e.__str__())
    result['cost'] = int((time.time() - start_time) * 1000)

    logger.info(result)

    return result


if __name__ == '__main__':
    # uvicorn.run(app='app:app', host="127.0.0.1", port=8000, reload=True, log_level='debug')
    uvicorn.run(app='app:app', host=config.host, port=config.port)

